package com.xsomnus.java_basic.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/7/19 0019 11:47
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class CglibProxy implements MethodInterceptor {


    private Class targetClass;

    public CglibProxy(Class targetClass) {
        this.targetClass = targetClass;
    }

    @SuppressWarnings("all")
    public <T> T getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("class =  " + o.getClass() + " superClass = " + methodProxy.getClass());
        System.out.println("开启事务");
        Object result = null;
        try {
            result = methodProxy.invokeSuper(o, args);
            System.out.println("提交事务");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("回滚事务");
        }
        return result;
    }
}
